package jzqb.service.impl;

import cnki.tpi.base.DataSourceManager;
import com.kbase.jdbc.ConnectionImpl;
import haha.life.common.BelongToSqlUtils;
import haha.life.common.CutPageBean;
import haha.life.common.RandomStringUtils;
import haha.life.common.SysTool;
import haha.life.normal.FileUtil;
import haha.life.normal.FileuploadUtils;
import haha.life.normal.TokenUtils;
import jzqb.bo.QBBKBo;
import jzqb.bo.StandKnowleageBo;
import jzqb.dao.AdminUserInfoDao;
import jzqb.dao.QBBKDao;
import jzqb.po.AdminUserPo;
import jzqb.po.AuthorityGroupPo;
import jzqb.po.QBBKPo;
import jzqb.po.QBBKTemplatePo;
import jzqb.service.QBBKService;
import jzqb.vo.QBBKVo;
import kbase.KBaseClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2020-09-22
 */
@Service
public class QBBKServiceImpl implements QBBKService {

    @Autowired
    private QBBKDao qbbkDao;
    @Autowired
    private AdminUserInfoDao userInfoDao;

    //情报百科封面存放基础地址
    @Value("${filePath.qbbkCoverPath}")
    private String qbbkCoverPath;

    //封面储存临时路径
    @Value("${filePath.coverTemPResource}")
    private String coverTemPResource;

    //数据库文件储存路径
    @Value("${filePath.dbBasePath}")
    private String dbBasePath;

    @Autowired
    private DataSourceManager kbaseDs;

    @Override
    public CutPageBean<QBBKVo> showQBBK(QBBKBo qbbkBo) {
        CutPageBean<QBBKVo> cutPage = new CutPageBean<>();
        List<QBBKVo> qbbkList = qbbkDao.showQBBKList(qbbkBo);
/*        for (QBBKVo qbbk : qbbkList) {
            String cover = qbbk.getCover();
            if (!"".equals(cover) && cover != null) {
                String absolutePath = qbbkCoverPath + "\\" + cover;
                byte[] imageBinary = FileuploadUtils.getImageBinary(absolutePath);
                qbbk.setCoverByte(imageBinary);
            }
        }*/
        int count = (int) qbbkDao.showQBBKCount(qbbkBo);
        cutPage.initCutPage(count, qbbkBo.getPageSize(), qbbkList);
        return cutPage;
    }

    @Override
    public QBBKVo showSingleQBBK(QBBKPo qbbkPo) {
        QBBKVo qbbkVo = qbbkDao.findQBBKBySysId(qbbkPo);
        //设置录入人姓名
        String[] split = qbbkVo.getRecorder().split("_");
        if (split.length == 2) {
            qbbkVo.setRecorderName(split[1]);
        } else {
            AdminUserPo user = userInfoDao.findUserById(qbbkVo.getAuthor());
            qbbkVo.setRecorderName(user.getName());
        }
        //设置封面
        String cover = qbbkVo.getCover();
        if (!"".equals(cover) && cover != null) {
            String absolutePath = qbbkCoverPath + "\\" + cover;
            byte[] imageBinary = FileuploadUtils.getImageBinary(absolutePath);
            qbbkVo.setCoverByte(imageBinary);
        }
        return qbbkVo;
    }

    @Override
    public Boolean addQBBK(QBBKPo qbbkPo) throws UnsupportedEncodingException {
        String recorderId = qbbkPo.getRecorder();
        AdminUserPo user = userInfoDao.findUserById(recorderId);
        //录入人  id_姓名
        String realRecorder = recorderId + "_" + user.getName();
        qbbkPo.setRecorder(realRecorder);
        //作者    id_姓名
        qbbkPo.setAuthor(realRecorder);
        Boolean insetBl = qbbkDao.addQBBK(qbbkPo);
        return insetBl;
    }


    @Override
    public Boolean updateQBBK(QBBKPo qbbkPo) throws UnsupportedEncodingException {
        //先查询出原来的数据
        QBBKPo oldQBBK = qbbkDao.getQBBKDetail(qbbkPo);
        Boolean bl = qbbkDao.updateQBBK(qbbkPo);
        Integer isUpdateCoverPath = qbbkPo.getIsUpdateCoverPath();
        //用户重新上传了封面-->需要删除原封面  并将新上传
        if (bl && isUpdateCoverPath == 1) {
            String oldCoverPath = oldQBBK.getCover();
            if (!"".equals(oldCoverPath) && oldCoverPath != null) {
                String[] split = oldCoverPath.split("\\\\");
                String oldFolderPath = qbbkCoverPath + "\\" + split[0] + "\\" + split[1] + "\\" + split[2];
                //删除原来记录的封面
                FileUtil.deleteFolder(oldFolderPath);
            }
            String coverPath = qbbkPo.getCover();
            if (!"".equals(coverPath) && coverPath != null) { //修改的封面不为空
                String fromPath = coverTemPResource + "\\" + coverPath;
                String toPath = qbbkCoverPath + "\\" + coverPath;
                Boolean moveCoverBoolean = false;
                try { //将上传的封面,从临时目录移动到正式目录
                    moveCoverBoolean = FileuploadUtils.fileMove(fromPath, toPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bl && moveCoverBoolean;
            }
        }
        return bl;
    }

    @Override
    public Boolean recallQBBK(QBBKPo qbbkPo) {
        return qbbkDao.recallQBBK(qbbkPo);
    }

    /**
     * 复制文件,并删除原文件
     *
     * @param s 文件的临时位置
     * @param t 文件的数据库目标位置
     * @return 执行结果
     */
    public Boolean moveTempFileToDBFile(String s, String t, String... arg) {
        ConnectionImpl conn = null;
        try {
            conn = (ConnectionImpl) this.kbaseDs.getConnection();
            int hCon = conn.getConnectionHset();
            KBaseClient kBaseClient = conn.getKbaseClient();
            //int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            String tPath = t.substring(0, t.lastIndexOf("\\"));
            String sPath = s.substring(0, s.lastIndexOf("\\"));
            int tempRet = kBaseClient.KBase_MakeDir(hCon, tPath);
            int nRet = kBaseClient.KBase_WriteFile(hCon, s, t);
            if (nRet < 0) {
                return false;
            } else if (nRet == 0) {
                //写入文件到DB正常,删除临时文件
                if (arg.length == 0) {
                    FileUtil.deleteFolder(sPath);
                } else {
                    if (arg[0].equals("notDeleteDir")) {
                    }
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (conn != null && !conn.isClosed())
                    conn.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    @Override
    public String uploading(MultipartFile file, String basePath) {
        String savePath = FileuploadUtils.uploading(file, basePath);
        return savePath;
    }

    @Override
    public List<StandKnowleageBo> getFieldNumByFlag(QBBKBo qbbkBo) {
        //加入随机数--防止缓存走DB缓存
        String randomString = RandomStringUtils.getRandomString(7);
        qbbkBo.setRandomString(randomString);
        return qbbkDao.getFieldNumByFlag(qbbkBo);
    }

    @Override
    public List<StandKnowleageBo> getDiffStatusQBBKNum(QBBKBo qbbkBo) {
        //加入随机数--防止缓存走DB缓存
        String randomString = RandomStringUtils.getRandomString(7);
        qbbkBo.setRandomString(randomString);
        //0:文件暂存  1:审核中  2:审核通过   3:审核未通过(包含退审和审核驳回)
        List<StandKnowleageBo> diffStatusQBBKNum = qbbkDao.getDiffStatusQBBKNum(qbbkBo);
        int size = diffStatusQBBKNum.size();
        //找出数量为0的
        if (size < 4 && size > 0) {
            String allKey = "0;1;2;3;";
            for (StandKnowleageBo standKnowleage : diffStatusQBBKNum) {
                String key = standKnowleage.getKey();
                if (allKey.contains(key)) {//如果含有key 就去掉相应的.如0;1;2;3;--->0;2;3;
                    allKey = allKey.replaceAll(key + ";", "");
                }
            }
            String[] split = allKey.split(";");
            for (String str : split) {
                StandKnowleageBo standKnowleage = new StandKnowleageBo();
                standKnowleage.setKey(str);
                standKnowleage.setValue("0");
                diffStatusQBBKNum.add(standKnowleage);
            }
        }

        if (diffStatusQBBKNum.size() == 0) {//查询出来全部为空
            StandKnowleageBo standKnowleage1 = new StandKnowleageBo();
            standKnowleage1.setKey("暂存中");
            standKnowleage1.setValue("0");
            StandKnowleageBo standKnowleage2 = new StandKnowleageBo();
            standKnowleage2.setKey("待审核");
            standKnowleage2.setValue("0");
            StandKnowleageBo standKnowleage3 = new StandKnowleageBo();
            standKnowleage3.setKey("审核通过");
            standKnowleage3.setValue("0");
            StandKnowleageBo standKnowleage4 = new StandKnowleageBo();
            standKnowleage4.setKey("审核未通过");
            standKnowleage4.setValue("0");
        } else { //查询出来不全部为空
            //把状态0123改为中文
            for (StandKnowleageBo standKnowleage : diffStatusQBBKNum) {
                String key = standKnowleage.getKey();
//            Integer num = Integer.valueOf(standKnowleage.getValue());
                switch (key) {
                    case "0":
                        standKnowleage.setKey("暂存中");
                        break;
                    case "1":
                        standKnowleage.setKey("待审核");
                        break;
                    case "2":
                        standKnowleage.setKey("审核通过");
                        break;
                    case "3":
                        standKnowleage.setKey("审核未通过");
                        break;
                }
            }
        }
        return diffStatusQBBKNum;
    }

    @Override
    public QBBKPo getQBBKDetail(QBBKPo qbbkPo) {
        return qbbkDao.getQBBKDetail(qbbkPo);
    }

    @Override
    public Boolean reviewQBBK(QBBKPo qbbkPo) {
        return qbbkDao.updateQBBKStatus(qbbkPo);
    }

    @Override
    public Boolean deleteQBBK(QBBKPo qbbkPo) {
        //先查询原来的数据-->便于删除封面
        QBBKPo oldQBBK = qbbkDao.getQBBKDetail(qbbkPo);
        Boolean delQBBK = qbbkDao.deleteQBBK(qbbkPo);
        if (delQBBK) {
            String oldCoverPath = oldQBBK.getCover();
            if (!"".equals(oldCoverPath) && oldCoverPath != null) {//封面不为空,删除本地封面
                String[] split = oldCoverPath.split("\\\\");
                String oldFolderPath = qbbkCoverPath + "\\" + split[0] + "\\" + split[1] + "\\" + split[2];
                //删除原来记录的封面
                FileUtil.deleteFolder(oldFolderPath);
            }
        }
        return delQBBK;
    }

    @Override
    public AuthorityGroupPo getAuditPersons(Integer AuditGroupId) {
        AuthorityGroupPo authorityGroupPo = qbbkDao.getUserMemberAndDeptMember(AuditGroupId);
        //去掉多余属性
        authorityGroupPo.setDepartMember("");
        authorityGroupPo.setUserMember("");
        //用户id字符串
        String userMemberId = authorityGroupPo.getUserMemberId();
        //部门id字符串
        String DepartMemberId = authorityGroupPo.getDepartMemberId();
        //部门成员和用户成员为空  直接返回
//        if ("".equals(userMemberId) && "".equals(DepartMemberId)) {
//            return authorityGroupPo;
//        }
        List<AdminUserPo> userListOne = null;
        List<AdminUserPo> userListTwo = null;
        List<AdminUserPo> totalUserList = null;
        String userNameStr = "";
        //根据部门id查询用户
        if (!"".equals(DepartMemberId) && DepartMemberId != null) {
            String[] splitDepartMemberId = DepartMemberId.split(";");
            String DepartMemberIdBelongToSql = BelongToSqlUtils.getBelongToSql(splitDepartMemberId, "所属部门");
            userListOne = qbbkDao.getUserByDepartBelongToSql(DepartMemberIdBelongToSql);
        }
        //根据用户id查询用户
        if (!"".equals(userMemberId) && userMemberId != null) {
            String[] splitUserMemberId = userMemberId.split(";");
            String UserMemberIdBelongToSql = BelongToSqlUtils.getBelongToSql(splitUserMemberId, "ID");
            userListTwo = qbbkDao.getUserByUserBelongToSql(UserMemberIdBelongToSql);
        }
        //去重
        if (userListOne != null && !userListOne.isEmpty() && userListTwo != null && !userListTwo.isEmpty()) {
            //两个集合都不为空
            userListOne.removeAll(userListTwo);
            userListOne.addAll(userListTwo);
            totalUserList = userListOne;
        }
        //通过部门查出来的集合为空
        if (userListOne == null || userListOne.isEmpty()) {
            totalUserList = userListTwo;
        }
        //通过用户查出来的集合为空
        if (userListTwo == null || userListTwo.isEmpty()) {
            totalUserList = userListOne;
        }
        if (totalUserList != null && !totalUserList.isEmpty()) {
            for (AdminUserPo adminUserPo : totalUserList) {
                String userName = adminUserPo.getName();
                if (!"".equals(userName) && userName != null) {
                    userNameStr += userName + ";";
                }
            }
        }
        if (!"".equals(userNameStr) && userNameStr != null) {
            String userNameSubString = userNameStr.substring(0, userNameStr.length() - 1);
            authorityGroupPo.setUserMember(userNameSubString);
        } else {
            authorityGroupPo.setUserMember(userNameStr);
        }
        //无用属性置空
        authorityGroupPo.setDepartMemberId("");
        authorityGroupPo.setUserMemberId("");
        return authorityGroupPo;
    }

    @Override
    public int findNewQBFWAuditData(QBBKBo qbbkBo) {
        int count = (int) qbbkDao.showQBBKCount(qbbkBo);
        return count;
    }

    @Override
    public Object addQBBKTemplate(QBBKTemplatePo qbbkTemplatePo, HttpServletRequest request) throws UnsupportedEncodingException {
        String templateName = qbbkTemplatePo.getTemplateName();
        List<String> allTemplateName = qbbkDao.findAllTemplateName();
        for (String str : allTemplateName) {
            if (str.equals(templateName)) {
                return SysTool.templateRepeat;
            }
        }
        String currentUserId = TokenUtils.getCurrentUserId(request);
       /* String templateText = qbbkTemplatePo.getTemplateText();
        if (!"".equals(templateName) && templateName != null) {
            String replaceTemplateName = templateName.replaceAll("'", "\'")
                    .replaceAll("\\\\\"", "\\\\\\\\\"");
            qbbkTemplatePo.setTemplateName(replaceTemplateName);
        }
        if (!"".equals(templateText) && templateText != null) {
            String replaceTemplateText = templateText.replaceAll("'", "\'")
                    .replaceAll("\\\\\"", "\\\\\\\\\"");
            qbbkTemplatePo.setTemplateText(replaceTemplateText);
        }*/
        qbbkTemplatePo.setCreatePerson(currentUserId);
        return qbbkDao.addQBBKTemplate(qbbkTemplatePo);
    }

    @Override
    public Object updateQBBKTemplate(QBBKTemplatePo qbbkTemplatePo) throws UnsupportedEncodingException {
        String templateName = qbbkTemplatePo.getTemplateName();
        List<String> allTemplateName = qbbkDao.findAllTemplateName();
        if (qbbkTemplatePo.getIsUpdateName() == 1) { //修改了文件名
            for (String str : allTemplateName) {
                if (str.equals(templateName)) {
                    return SysTool.templateRepeat;
                }
            }
        }
/*        String templateText = qbbkTemplatePo.getTemplateText();
        if (!"".equals(templateName) && templateName != null) {
            String replaceTemplateName = templateName.replaceAll("'", "\'")
                    .replaceAll("\\\\\"", "\\\\\\\\\"");
            qbbkTemplatePo.setTemplateName(replaceTemplateName);
        }
        if (!"".equals(templateText) && templateText != null) {
            String replaceTemplateText = templateText.replaceAll("'", "\'")
                    .replaceAll("\\\\\"", "\\\\\\\\\"");
            qbbkTemplatePo.setTemplateText(replaceTemplateText);
        }*/
        return qbbkDao.updateQBBKTemplate(qbbkTemplatePo);
    }

    @Override
    public List<QBBKTemplatePo> showTemplateList() {
        return qbbkDao.showTemplateList();
    }

    @Override
    public Boolean delQBBKTemplate(Integer id) {
        return qbbkDao.delQBBKTemplate(id);
    }
}